package com.tiancheng.trade.authserver.component.login.impl;

import com.tiancheng.trade.authserver.component.login.BaseUserLoginHandler;
import com.tiancheng.trade.authserver.entity.AuthUser;
import com.tiancheng.trade.authserver.enums.LogInTypeEnum;
import com.tiancheng.trade.authserver.enums.ThirdPlatformEnums;
import com.tiancheng.trade.authserver.enums.TokenTypeEnum;
import com.tiancheng.trade.authserver.service.IAuthUserService;
import com.tiancheng.trade.authserver.utils.PasswordService;
import com.tiancheng.trade.authserver.vo.UserLoginInVO;
import com.tiancheng.trade.commom.core.exception.error.AuthErrorInfoEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 密码登录
 */
@Component("passwordSignInHandler")
public class PasswordSignInHandler extends BaseUserLoginHandler {
    @Resource
    private IAuthUserService userService;
    @Resource
    private PasswordService passwordService;


    @Override
    protected void paramValidate(UserLoginInVO param, boolean checkCertificate) {
        AuthErrorInfoEnum.AUTH_PWD_NULL_ERROR.assertNotEmpty(param.getPassword());
        String email = param.getEmail();
        String phone = param.getPhone();
        AuthErrorInfoEnum.AUTH_PHONE_AND_EMAIL_BOTH_IS_NULL.assertIsTrue(StringUtils.isNotEmpty(email) || StringUtils.isNotEmpty(phone));
        param.setThirdPlatform(ThirdPlatformEnums.tiancheng);
        if (StringUtils.isNotEmpty(email)) {
            param.setTokenType(TokenTypeEnum.web_email);
        } else {
            param.setTokenType(TokenTypeEnum.web_phone);
        }
        param.setClientId(this.platformRequestProperties.getClientId());
    }

    /**
     * 校验密码有效期
     */
    protected void validatePasswordExpired(AuthUser user, UserLoginInVO param) {
        this.passwordService.validatePasswordExpired(user);
    }

    /**
     * 校验密码
     */
    protected void validatePassword(AuthUser user, UserLoginInVO param, boolean checkCertificate) {
        if (checkCertificate) {
            AuthErrorInfoEnum.AUTH_PWD_HAS_EXPIRED.assertNotEmpty(user.getPassword());
            this.validatePasswordExpired(user, param);
            this.passwordService.validateRight(user, param.getPassword());
        }
    }

    @Override
    protected AuthUser getUserByParam(UserLoginInVO param, boolean checkCertificate) {
        String email = param.getEmail();
        String phone = param.getPhone();
        AuthUser user;
        if (StringUtils.isNotEmpty(email)) {
            user = this.userService.getByEmail(email);
        } else {
            user = this.userService.getByPhone(phone);
        }
        AuthErrorInfoEnum.AUTH_USER_ACCOUNT_DOES_NOT_EXIST.assertNotNull(user);
        this.validatePassword(user, param, checkCertificate);
        return user;
    }

    @Override
    public LogInTypeEnum getHandleType() {
        return LogInTypeEnum.Password;
    }
}
